//
// Created by 32827 on 2024/5/17.
//

#include "user.h"
#include "stm32f4xx.h"
#include "string.h"
#include "yzl.h"
#include "user_ui.h"

YZF_RECV yzf_recv_data;
//YZL_Soft_SPI SD_SPI={YZL_SOFTPORT_SPI_MODE_3,YZF_TRUE,{YZF_PIN_4,GPIOC},{YZF_PIN_5,GPIOA},{YZF_PIN_7,GPIOA},{YZF_PIN_6,GPIOA}};
YZF_SPI_POINTER MicroSD_SPI=SPI1;
static __attribute__((section(".ccmram"))) char mem[48*1024];
YZ_MemManger yzlMem={(uint32_t) &(mem[0]), 32 * 1024, 0, 0};
YZ_MemManger freeRTOSMem={0,0,0,0};
int __io_putchar(int ch){
    yz_uart_transmit(USART1,(uint8_t *)&ch,1);
    return ch;
}
int __io_getchar(void){
    uint8_t ch;
    yz_uart_receive_IT(USART1,&ch,1);
    return ch;
}
/** ====================   文件系统    =================== **/
uint8_t dsdata[2048];
YZF_BOOL file_init(void){
    FRESULT res_sd= f_mount(&yzl_fs,"/MMC/",1);
    if (res_sd == FR_NO_FILESYSTEM) {
        yz_info("》SD卡还没有文件系统，即将进行格式化...\n");
        res_sd=f_mkfs("/MMC/",0,dsdata,2048);
        if (res_sd == FR_OK) {
            yz_info("》SD卡已成功格式化文件系统。\n");
            res_sd = f_mount(&yzl_fs,"/MMC/",1);
            return YZF_TRUE;
        } else {
            yz_error("《《格式化失败。》》\n");
            return YZF_FALSE;
        }
    } else if (res_sd!=FR_OK) {
        yz_error("！！SD卡挂载文件系统失败。(%d)\n",res_sd);
        yz_error("！！可能原因：SD卡初始化不成功。\n");
        return YZF_FALSE;
    }else{
        yz_info("文件挂载成功\n");
        return YZF_TRUE;
    }
}
/** ====================    END   =================== **/
/*
FIL fnew;
UINT fnum;
BYTE ReadBuffer[1024]= {0};
FRESULT res_sd=f_open(&fnew,"/MMC/FatFs读写测试文件.txt",FA_OPEN_EXISTING|FA_READ);
if (res_sd == FR_OK) {
    yz_info("》打开文件成功。\r\n");
    res_sd = f_read(&fnew, ReadBuffer, sizeof(ReadBuffer), &fnum);
    if (res_sd==FR_OK) {
        yz_info("》文件读取成功,读到字节数据：%d\r\n",fnum);
        yz_info("》读取得的文件数据为：\r\n%s \r\n", ReadBuffer);
    } else {
        yz_error("！！文件读取失败：(%d)\n",res_sd);
    }
} else {
    yz_error("！！打开文件失败。\r\n");
}

f_close(&fnew);
*/
YZF_RESULT Uart_Test(){
    yz_info("=====内存打印=====\n");
    yzl_mem_print();
    yz_recv_transmit_reset();
    return YZF_OK;
}
YZF_GLOBAL_INDEX ui_handler;
int user_main(){
    yzl_mem_init(&yzlMem);
    freeRTOSMem.pMalloc=pvPortMalloc;
    freeRTOSMem.pFree=vPortFree;
    yz_time_init_tim(168*1000*1000);

    yz_uart_init(USART1,YZF_UART_LENGTH_8,0,YZF_UART1_BAUDRATE_115200,YZF_FALSE);
    yz_uart_receive_IT_init(USART1);
    yz_recv_transmit_init(USART1);
    yz_recv_transmit_handler_set(0x00000001,Uart_Test);

    yzf_area_recv_init(&yzf_recv_data,NULL);

    //Init I2C1
    ///I2c LCD1306 初始化
    YGPIO(GPIOB)
    YPIN(YZF_PIN_6)
    yzf_gpio_set_AFOD_();
    yzf_gpio_set_HIGH_();
    YPIN(YZF_PIN_7)
    yzf_gpio_set_AFOD_();
    yzf_gpio_set_HIGH_();

    yz_i2c_add7_high_open(I2C1,0x00,YZ_I2C123_Freq);


    // Init SPI1
    YGPIO(GPIOC)
    YPIN(YZF_PIN_4)
    yzf_gpio_open_clock_();
    yzf_gpio_set_PP_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_1_();
    YGPIO(GPIOA)
    YPIN(YZF_PIN_7)
    yzf_gpio_open_clock_();
    yzf_gpio_set_AFPP_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_1_();
    yzf_gpio_set_af_(5);
    YPIN(YZF_PIN_5)
    yzf_gpio_set_AFPP_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_1_();
    yzf_gpio_set_af_(5);
    YPIN(YZF_PIN_6)
    yzf_gpio_set_AFPP_();
    yzf_gpio_set_HIGH_();
    yzf_gpio_set_af_(5);


    yz_spi_init_full_lines(SPI1);

    char *p="测试\r\n";
    yz_info(p);

    file_init();


    yzl_font_init("FontBin16");
    yz_info("字体系统加载成功\n");

    yzl_ui_init(BLACK);
//    yzl_ui_draw_circle(20,40,10,YZF_TRUE,WHITE);
//    yzl_1306_refresh(I2C1);

//    char *src_text="你好,世界!";
//    yzl_iconv_clear_ucs2_buf();
//    utf2ucs(yzl_iconv_ucs2_buf, (unsigned char *)src_text);
//    uint16_t len= yzl_iconv_ucs2_strlen(yzl_iconv_ucs2_buf);
//    uint8_t *dst_text = YZL_MEM_MANAGER.pMalloc(len*2+1);
//    uint16_t textLen = len;
//    memcpy(dst_text, yzl_iconv_ucs2_buf, len*2+1);
//
//    yzl_ui_draw_string(0,0,128,dst_text,textLen,BLACK,WHITE);
//    yzl_1306_refresh(I2C1);

//    YZL_MEM_MANAGER.pFree(dst_text);


    //ui初始化线程
    yzf_global_handler_add(user_yz_thread_ui_main_init);
    //ui Loop 线程
    ui_handler=yzf_global_handler_add(user_yz_thread_ui_main);

    return 0;
}
YZF_BOOL OutError=YZF_FALSE;
//跳出错误函数
void user_OutError(){
    OutError=YZF_TRUE;
}

void user_error_handler(YZF_RESULT error){
    switch (error) {
        case YZF_NOT_FOUND:
            yz_error("[GlobalSheet: %hd] 参数未找到.\n",yz_status_sheet_get(YZ_FLAG_ERROR_HANDLER_INDEX));
            break;
        case YZF_ERROR:
            yz_error("[GlobalSheet: %hd] 未知错误.\n",yz_status_sheet_get(YZ_FLAG_ERROR_HANDLER_INDEX));
            break;
        case YZF_NOT_INIT:
            yz_error("[GlobalSheet: %hd] 使用的函数，所需对象未被初始化.\n",yz_status_sheet_get(YZ_FLAG_ERROR_HANDLER_INDEX));
            break;
        case YZF_CRC_ERROR:
            yz_error("[GlobalSheet: %hd] CRC校验错误.\n",yz_status_sheet_get(YZ_FLAG_ERROR_HANDLER_INDEX));
            break;
        case YZF_CLOCK_NOT_READY:
            yz_error("[GlobalSheet: %hd] 时钟未就绪.\n",yz_status_sheet_get(YZ_FLAG_ERROR_HANDLER_INDEX));
            break;
        case YZF_NOTHING:
#ifdef osCMSIS
            osDelay(1);
#endif
#ifdef GD32F470
            vTaskDelay(1);
#endif
            user_OutError();
            break;
        default:
            yz_error("[GlobalSheet: %hd] 未被识别的错误类型. Code: %d\n",yz_status_sheet_get(YZ_FLAG_ERROR_HANDLER_INDEX),error);
    }
    while (!OutError){
        __asm__("nop");
    }
    OutError=YZF_FALSE;
}
void yz_error(const char *fmt, ...){
    char *str_error="[ERROR]";
    int i;

    va_list arg;
    va_start(arg, fmt);
    memset(transmit_buf,0,sizeof(transmit_buf));
    i = vsprintf(transmit_buf, fmt, arg);
    va_end(arg);

    yz_uart_transmit(USART1,(uint8_t *)str_error, strlen(str_error));
    yz_uart_transmit(USART1,(uint8_t *)transmit_buf,i);
//    if(Yz_FontInitFlag){
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,(YZ_COLOR)RED,(unsigned char *)str_error);
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,(YZ_COLOR)RED,(unsigned char *)transmit_buf);
//    }
}
void yz_info(const char *fmt, ...){
    char *str_error="[INFO]";
    int i;

    va_list arg;
    va_start(arg, fmt);
    memset(transmit_buf,0,sizeof(transmit_buf));
    i = vsprintf(transmit_buf, fmt, arg);
    va_end(arg);

    yz_uart_transmit(USART1,(uint8_t *)str_error, strlen(str_error));
    yz_uart_transmit(USART1,(uint8_t *)transmit_buf,i);
//    if(Yz_FontInitFlag){
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,(YZ_COLOR)WHITE,(unsigned char *)str_error);
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,(YZ_COLOR)WHITE,(unsigned char *)transmit_buf);
//    }
}
void yz_debug(const char *fmt, ...){
    char *str_error="[DEBUG]";
    int i;

    va_list arg;
    va_start(arg, fmt);
    memset(transmit_buf,0,sizeof(transmit_buf));
    i = vsprintf(transmit_buf, fmt, arg);
    va_end(arg);

    yz_uart_transmit(USART1,(uint8_t *)str_error, strlen(str_error));
    yz_uart_transmit(USART1,(uint8_t *)transmit_buf,i);
//    if(Yz_FontInitFlag){
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,(YZ_COLOR)YELLOW,(unsigned char *)str_error);
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,(YZ_COLOR)YELLOW,(unsigned char *)transmit_buf);
//    }
}
void yz_ok(const char *fmt, ...){
    char *str_error="[SUCCESS]";
    int i;

    va_list arg;
    va_start(arg, fmt);
    memset(transmit_buf,0,sizeof(transmit_buf));
    i = vsprintf(transmit_buf, fmt, arg);
    va_end(arg);

    yz_uart_transmit(USART1,(uint8_t *)str_error, strlen(str_error));
    yz_uart_transmit(USART1,(uint8_t *)transmit_buf,i);
//    if(Yz_FontInitFlag){
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,GREEN,(unsigned char *)str_error);
//        USER_SCREEN_WRITE_TEXT_UTF8((YZ_COLOR)BLACK,GREEN,(unsigned char *)transmit_buf);
//    }
}